package netService

import (
	"net"
	"sync"
)


// receiveTask 客户端请求内容
type receiveUdpTask struct {
	Conn        *net.UDPConn                  //连接对象
	RemoteAddr  net.Addr                      //远程节点
	ConnId      uint64                        //连接ID
	Data        []byte                        //客户端请求的数据
	Count       int                           //数据长度
	OnCompleted func(receive *receiveUdpTask) //接收到一次数据(未分包开始处理不确定是否完成)
}

//回收
func (r *receiveUdpTask) recovery() {
	r.Conn = nil
	r.RemoteAddr = nil
	r.ConnId = 0
	r.Count = 0
	r.OnCompleted = nil
}

// GetTaskId 获取连接id
func (r *receiveUdpTask) GetTaskId() uint64 {
	return r.ConnId
}

// RunTask 处理数据
func (r *receiveUdpTask) RunTask() {
	r.OnCompleted(r)
}

type receiveUdpTaskPool struct {
	bufferSize  uint
	bytePool    *sync.Pool
}

//udp 任务处理池
func newReceiveUdpTaskPool(bufferSize uint) *receiveUdpTaskPool {
	pool := &receiveUdpTaskPool{
		bufferSize: bufferSize,
		bytePool: &sync.Pool{
			New: func() interface{} {
				data := make([]byte, bufferSize)
				return &receiveUdpTask{
					Data: data,
				}
			},
		},
	}
	return pool
}

// Put 回收
func (b *receiveUdpTaskPool) Put(task *receiveUdpTask) {
	task.recovery()
	b.bytePool.Put(task)
}

// Get 获取
func (b *receiveUdpTaskPool) Get() *receiveUdpTask {
	return b.bytePool.Get().(*receiveUdpTask)
}